/*
 *所有关于equipmentfaultmaintenanceview类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*equipmentfaultmaintenanceviewService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VolPro.Core.BaseProvider;
using VolPro.Core.Extensions.AutofacManager;
using VolPro.Entity.DomainModels;
using System.Linq;
using VolPro.Core.Utilities;
using System.Linq.Expressions;
using VolPro.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using SMes.DbMethod.IRepositories;
using System.Net;
using VolPro.Core.ManageUser;
using SMes.DbMethod.IServices;
using Microsoft.AspNetCore.Mvc.RazorPages;
using OfficeOpenXml;

namespace SMes.DbMethod.Services
{
    public partial class equipmentfaultmaintenanceviewService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IequipmentfaultmaintenanceviewRepository _repository;//访问数据库
        private readonly IequipmentRepository _equipmentRepository;
        private readonly IequipmentfaultmaintenanceRepository _equipmentfaultmaintenanceRepository;

        [ActivatorUtilitiesConstructor]
        public equipmentfaultmaintenanceviewService(
            IequipmentfaultmaintenanceviewRepository dbRepository,
            IequipmentRepository equipmentRepository,
            IequipmentfaultmaintenanceRepository equipmentfaultmaintenanceRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _equipmentRepository = equipmentRepository;
            _equipmentfaultmaintenanceRepository = equipmentfaultmaintenanceRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public override WebResponseContent Add(SaveModel saveDataModel)
        {

            saveDataModel.MainData.Remove("SerialNo");
            saveDataModel.MainData.Remove("EquipmentName");

            return equipmentfaultmaintenanceService.Instance.Add(saveDataModel);
        }
        public override WebResponseContent Update(SaveModel saveModel)
        {
            saveModel.MainData.Remove("SerialNo");
            saveModel.MainData.Remove("EquipmentName");
            return equipmentfaultmaintenanceService.Instance.Update(saveModel);
        }
        public override WebResponseContent Import(List<IFormFile> files)
        {
            var webResponse = new WebResponseContent();
            ImportOnExecuting = (List<equipmentfaultmaintenanceview> list) =>
            {
                var repdata = list.GroupBy(x => x.Tag).Where(m => m.Count() > 1).Select(m => m.Key).ToList();
                if (repdata != null && repdata.Count > 0)
                {
                    return webResponse.Error($"Excel中存在[字段标识]重复的数据,重复的[字段标识(Tag)]:{string.Join(";", repdata)}");
                }
                var SerialNoList = list.Select(x => x.SerialNo).Distinct().ToList();
                var equipmentList = _equipmentRepository.FindAsIQueryable(x => SerialNoList.Contains(x.SerialNo)).Select(x => new
                {
                    x.EquipmentID,
                    x.SerialNo
                }).ToList();
                var eqSerialNoList = equipmentList.Select(x => x.SerialNo).ToList();
                var noEqList = SerialNoList.Except(eqSerialNoList).ToList();
                if (noEqList != null && noEqList.Count > 0)
                {
                    return webResponse.Error($"数据库中不存在Excel中[设备编号],不存在的的[设备编号(SerialNo)]:{string.Join(";", noEqList)}");
                }
                var equipmentFaultMaintenanceList = new List<equipmentfaultmaintenance>();
                foreach (var item in list)
                {
                    var equipmentFaultMaintenance = new equipmentfaultmaintenance()
                    {
                        EquipmentID = equipmentList.Where(x => item.SerialNo == x.SerialNo).Select(x => x.EquipmentID).FirstOrDefault(),
                        FieldName = item.FieldName,
                        Tag = item.Tag,
                        FieldValue = item.FieldValue,
                        FaultReason = item.FaultReason,
                        Resolution = item.Resolution,
                        Level = item.Level,
                        UpdateTime = DateTime.Now,
                        OperatorID = UserContext.Current.UserTrueName,
                        Memo = item.Memo
                    };
                    equipmentFaultMaintenanceList.Add(equipmentFaultMaintenance);
                }
                var tags = list.Select(x => x.Tag).ToList();
                var existingIDs = _equipmentfaultmaintenanceRepository.FindAsIQueryable(t => tags.Contains(t.Tag)).Select(t => new {
                    t.Tag,
                    t.FaultID
                }).ToList();
                var existingTags = existingIDs.Select(t => t.Tag).ToList();
                var toAdd = equipmentFaultMaintenanceList.Where(x => !existingTags.Contains(x.Tag)).ToList();
                //var  toUpdate=equipmentFaultMaintenanceList.Where(x=>existingTags.Contains(x.Tag)).ToList();

                //  需要更新的 tag 如果不唯一，重新定义唯一字段
                var toUpdate = equipmentFaultMaintenanceList.Join(existingIDs, u => u.Tag, t => t.Tag,
                    (u, t) => new equipmentfaultmaintenance{
                        FaultID = t.FaultID,
                        EquipmentID = u.EquipmentID,
                        Tag = t.Tag,
                        FieldValue = u.FieldValue,
                        FaultReason = u.FaultReason,
                        Resolution = u.Resolution,
                        Level = u.Level,
                        UpdateTime = DateTime.Now,
                        OperatorID = UserContext.Current.UserTrueName,
                        Memo = u.Memo
                    }).ToList();
                string message = null;
                if (toUpdate != null && toUpdate.Count > 0)
                {
                    var tagsRe = toUpdate.Select(x => x.Tag).ToList();
                    message = $"数据库与Excel有重复[字段标识]，重复[字段标识]已做更新处理。重复的[字段标识(Tag)]:{string.Join(";", tagsRe)}";
                }
                _equipmentfaultmaintenanceRepository.AddRange(toAdd);
                _equipmentfaultmaintenanceRepository.UpdateRange(toUpdate);
                _equipmentfaultmaintenanceRepository.SaveChanges();
                return webResponse.OK(message);
            };
            // 定义ViewImport 不保存到数据库
            return base.ViewImport(files);
        }
        public override WebResponseContent Del(object[] keys, bool delList = true)
        {
            return equipmentfaultmaintenanceService.Instance.Del(keys, delList);
            //return base.Del(keys, delList);
        }
    }
}
